Array.prototype.mergeSort = function() {
  /**
   *
   * @param {Array} left 左边数组
   * @param {Array} right 右边数组
   */
  const merge = (left, right) => {
    const result = [];
    let il = 0,
      ir = 0;

    while (il < left.length && ir < right.length) {
      if (left[il] < right[ir]) {
        result.push(left[il++]);
      } else {
        result.push(right[ir++]);
      }
    }

    while (il < left.length) {
      result.push(left[il++]);
    }

    while (ir < right.length) {
      result.push(right[ir++]);
    }

    return result;
  };

  /**
   *
   * @param {Array} array 待排序数组
   */
  const mergeSortRec = array => {
    if (array.length === 1) {
      return array;
    }
    const mid = Math.floor(array.length / 2);
    const left = array.slice(0, mid);
    const right = array.slice(mid, array.length);
    return merge(mergeSortRec(left), mergeSortRec(right));
  };

  return mergeSortRec(this);
};

console.log([5, 4, 3, 2, 1].mergeSort()); // Array(5) [1, 2, 3, 4, 5]
